package com.wmlive.hhvideo.heihei.mainhome.adapter;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.AppCacheFileUtils;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.dcijkplayerlib.AbsIjkPlayListener;
import com.wmlive.hhvideo.dcijkplayerlib.DcIjkPlayer;
import com.wmlive.hhvideo.dcijkplayerlib.DcIjkPlayerManager;
import com.wmlive.hhvideo.dcijkplayerlib.Proxy;
import com.wmlive.hhvideo.dcijkplayerlib.utils.L;
import com.wmlive.hhvideo.heihei.beans.main.RefreshCommentBean;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoInfoResponse;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoItem;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoLoveResponse;
import com.wmlive.hhvideo.heihei.beans.main.UserBehavior;
import com.wmlive.hhvideo.heihei.beans.main.UserFanRelation;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.mainhome.presenter.ShortVideoViewCallback;
import com.wmlive.hhvideo.heihei.mainhome.viewholder.RecommendNewViewHolder;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshAdapter;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;
import com.wmlive.networklib.util.RxBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.wmlive.hhvideo.R;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by lsq on 6/19/2017.
 * 推荐页的adapter
 */

public class RecommendNewAdapter extends RefreshAdapter<RecommendNewViewHolder, ShortVideoItem> {

    public final static String TAG = "RecommendNewAdapter";
    private ShortVideoViewCallback shortVideoViewCallback;
    private LinearLayoutManager linearLayoutManager;
    private int currentPosition = -1;
    private int refreshType = 0;
    private int videoType;
    private RecommendNewViewHolder currentViewHolder;
    //    private DcIjkPlayer dcIjkPlayer;
    private boolean isScrollUp = true;//是上滑
    private int lastScrollY;//上次滑动y的位置
    private int nextPosition;//下次拉取数据的位置
    private int randomId;
    private boolean buffered;//视频已经完成缓存
    private CompositeDisposable compositeDisposable;
    private Disposable cacheDisposable;
    private DcIjkPlayer cachePlayer;

    public RecommendNewAdapter(int videoType, int pageSize, List<ShortVideoItem> list, RefreshRecyclerView refreshView,
                               LinearLayoutManager layoutManager,
                               ShortVideoViewCallback clickListener) {
        super(list, refreshView, pageSize);
        this.videoType = videoType;
        linearLayoutManager = layoutManager;
        shortVideoViewCallback = clickListener;
        compositeDisposable = new CompositeDisposable();
//        dcIjkPlayer = new DcIjkPlayer(refreshView.getContext());
//        dcIjkPlayer.setCanLoop(true);
//        dcIjkPlayer.setPlayListener(playListener);
//        dcIjkPlayer.setCacheFile(AppCacheFileUtils.getAppVideoCachePathFile(DCApplication.getDCApp()));
        randomId = getRandom(1000000, 9999999);
        cachePlayer = new DcIjkPlayer(DCApplication.getDCApp(), true);
        DcIjkPlayerManager.get().setCanLoop(true);
        DcIjkPlayerManager.get().setPlayListener(randomId, playListener);
        DcIjkPlayerManager.get().setCacheFile(AppCacheFileUtils.getAppVideoCachePathFile(DCApplication.getDCApp()));
        refreshView.getRecycleView().addOnScrollListener(onScrollListener);
    }

    @Override
    public RecommendNewViewHolder onCreateHolder(ViewGroup parent, int viewType) {
        return new RecommendNewViewHolder(parent, R.layout.item_recomment_new);
    }

    @Override
    public void onBindHolder(RecommendNewViewHolder holder, int position, ShortVideoItem data) {
        holder.initData(videoType, position, data, shortVideoViewCallback, this);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            KLog.i("=====onScrollStateChanged:" + newState);
            if (newState == 0) {
                forcePlay(true);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            isScrollUp = (dy - lastScrollY > 0);
        }
    };

    public void forcePlay(boolean needDetail) {
        int firstP = linearLayoutManager.findFirstVisibleItemPosition();
        int lastP = linearLayoutManager.findLastVisibleItemPosition();
        KLog.i("===firstP:" + firstP + " lastP:" + lastP + "   currentPosition:" + currentPosition);
        if (firstP != -1
                && (firstP == lastP)
                && (firstP == 0 && currentPosition == 0 || currentPosition != firstP)
                && isContent(firstP)
                && getItemData(firstP) != null) {
            preparePlay(needDetail, firstP);
        } else if (firstP != -1
                && firstP != lastP
                && isContent(lastP)) {
            KLog.i("===位置不对，滚动调整位置到：" + (isScrollUp ? firstP : lastP));
            // TODO: 6/30/2017
//            getRecycleView().getRecycleView().scrollToPosition(isScrollUp ? firstP : lastP);
        }
    }

    public void preparePlay(boolean needDetail, int firstP) {
        currentPosition = firstP;
        ShortVideoItem shortVideoItem = getItemData(currentPosition);
        if (shortVideoItem != null && !TextUtils.isEmpty(shortVideoItem.getOpus_path())
                && !shortVideoItem.getOpus_path().equals(DcIjkPlayerManager.get().getUrl())) {
            KLog.i("====url不一样，可以重新播放");
            if (shortVideoItem.getUser() != null && shortVideoItem.getUser().getId() > 0) {
                if (shortVideoViewCallback != null) {
                    shortVideoViewCallback.getUserInfo(shortVideoItem.getUser().getId());
                }
//                RxBus2.get().send(GlobalParams.EventType.TYPE_GET_USER_INFO, shortVideoItem.getUser().getId());
//                KLog.i("=====发送消息，获取用户的个人信息");
            }
            findCurrentViewHolder();
            KLog.i("======preparePlay1:" + currentViewHolder);
            if (currentViewHolder != null) {
                if (null != shortVideoViewCallback) {
                    if (needDetail && shortVideoItem.getIs_delete() == 0) {//获取视频详情
                        KLog.i("======preparePlay4");
                        shortVideoViewCallback.getVideoDetail(currentPosition, getItemData(currentPosition).getId());
                    }
                    if (videoType != RecommendFragmentNew.TYPE_SINGLE_WORK
                            && currentPosition >= (getDataContainer().size() - 2)
                            && (nextPosition < getDataContainer().size())) {//触发拉取下一页的数据
                        KLog.i("======拉取下一页的数据");
                        nextPosition = getDataContainer().size();
                        shortVideoViewCallback.getNextPageList(nextPosition);
                    }
                }
                if (shortVideoItem.getIs_delete() == 1) {//视频在列表中已被删除
                    onVideoError(DCApplication.getDCApp().getString(R.string.stringWorkDeleted));
                } else {
                    KLog.i("======preparePlay2");
//                    if (currentPosition == 3) {//测试一下
//                        ToastUtil.showToast("该视频已删除");
//                        if (null != currentViewHolder) {
//                            currentViewHolder.dismissVideoLoading();
//                            dcIjkPlayer.setClickPause(false);
//                        }
//                    } else {
                    DcIjkPlayerManager.get().setClickPause(true);
                    DcIjkPlayerManager.get().attachPlayer(currentViewHolder.flPlayerContainer, new DcIjkPlayerManager.OnPlayerDetachListener() {
                        @Override
                        public void onDetach() {
                            KLog.i("=======onDetach1 preparePlay");
                            if (currentViewHolder != null) {
                                KLog.i("=======onDetach2 preparePlay");
                                currentViewHolder.setCoverVisible(true);
                            }
                        }
                    });
                    buffered = false;
                    KLog.i("======preparePlay3");
                    if (GlobalParams.StaticVariable.sCurrentNetwork == 1 && !GlobalParams.StaticVariable.sAllowdMobile) {
                        if (shortVideoViewCallback != null) {
                            shortVideoViewCallback.onMobileNetwork();
                        }
                    } else {
                        allowPlay();
                    }

                    //预加载后面三张封面图片
                    for (int i = 0; i < 3; i++) {
                        ShortVideoItem item = getItemData(currentPosition + i);
                        if (null != item) {
                            compositeDisposable.add(
                                    Observable.just(item.getOpus_cover())
                                            .subscribeOn(Schedulers.io())
                                            .map(new Function<String, Integer>() {
                                                @Override
                                                public Integer apply(String url) throws Exception {
                                                    GlideLoader.downloadImage(DCApplication.getDCApp(), url);
                                                    return 1;
                                                }
                                            })
                                            .subscribe());
                        }
                    }
                }
            }
        }
    }

    //允许播放
    public void allowPlay() {
        ShortVideoItem shortVideoItem = getItemData(currentPosition);
        if (shortVideoItem != null) {
            DcIjkPlayerManager.get().setClickPause(true);
            DcIjkPlayerManager.get().setVideoUrl(randomId, shortVideoItem.getId(), shortVideoItem.getOpus_path());
//            cacheNextVideo(shortVideoItem.getOpus_path(), true);
        }
    }

    /**
     * 缓存下一个视频
     *
     * @param currentUrl
     */
    private void cacheNextVideo(String currentUrl, boolean needDelay) {
        //缓存下一个视频
        final ShortVideoItem next = getItemData(currentPosition + 1);
        if (next != null && !Proxy.get().getProxyServer().isCached(next.getOpus_path())) {
            if (cacheDisposable != null && !cacheDisposable.isDisposed()) {
                cacheDisposable.dispose();
            }
            cacheDisposable = Observable.just(currentUrl)
                    .delay(needDelay ? 3 : 0, TimeUnit.SECONDS)
                    .repeat(Proxy.get().getProxyServer().isCached(currentUrl) ? 1 : 3)
                    .subscribeOn(Schedulers.io())
                    .map(new Function<String, Boolean>() {
                        @Override
                        public Boolean apply(@NonNull String url) throws Exception {
                            return Proxy.get().getProxyServer().isCached(url);
                        }
                    })
                    .observeOn(Schedulers.io())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            KLog.i("======" + (aBoolean ? "可以" : "不可以") + "缓存下一个视频");
                            if (aBoolean) {
                                if (!Proxy.get().getProxyServer().isCached(next.getOpus_path())) {
                                    if (cachePlayer == null) {
                                        cachePlayer = new DcIjkPlayer(DCApplication.getDCApp(), true);
                                    }
                                    KLog.i("======开始缓存下一个视频");
                                    cachePlayer.loadCacheVideo(next.getOpus_path(), AppCacheFileUtils.getAppVideoCachePathFile(DCApplication.getDCApp()));
                                }
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(@NonNull Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
        }
    }

    //移动网络不允许播放
    public void disallowPlay() {
        if (currentViewHolder != null) {
            currentViewHolder.dismissVideoLoading();
            DcIjkPlayerManager.get().setClickPause(false);
        }
    }

    private void findCurrentViewHolder() {
        KLog.i("======findCurrentViewHolder1");
        if (currentPosition != -1) {
            KLog.i("======findCurrentViewHolder2");
            RecyclerView.ViewHolder view = getRecycleView().getRecycleView().findViewHolderForAdapterPosition(currentPosition);
            if (null != view && view instanceof RecommendNewViewHolder) {
                KLog.i("========viewHolder:" + view.getClass().getSimpleName());
                currentViewHolder = (RecommendNewViewHolder) view;
            }
        }
    }

    public void showVideoCover(boolean show) {
        if (currentViewHolder != null) {
            currentViewHolder.setCoverVisible(show);
        }
    }

    private AbsIjkPlayListener playListener = new AbsIjkPlayListener() {

        @Override
        public void onLoopStart() {
            super.onLoopStart();
            if (null != currentViewHolder) {
                ShortVideoItem shortVideoItem = getItemData(currentPosition);
                if (null != shortVideoItem && shortVideoItem.getIs_delete() == 1) {
                    onVideoError(DCApplication.getDCApp().getString(R.string.stringWorkDeleted));
                }
            }
        }

        @Override
        public void onPlayPreparing() {
            if (null != currentViewHolder) {
                currentViewHolder.setPlayIcon(true);
                if (getItemData(currentPosition) != null
                        && Proxy.get().getProxyServer() != null
                        && Proxy.get().getProxyServer().isCached(getItemData(currentPosition).getOpus_path())) {
                    currentViewHolder.dismissVideoLoading();
                } else {
                    currentViewHolder.showVideoLoading();
                }
            }
        }

        @Override
        public void onPlayPrepared() {
            KLog.i("=====onPlayPrepared11111");
            currentViewHolder.setPlayIcon(true);
            DcIjkPlayerManager.get().startPlay();
        }

        @Override
        public void onAudioRenderingStart() {
            if (null != currentViewHolder) {//以这里开始播放为准
                currentViewHolder.dismissVideoLoading();
                KLog.i("=====onAudioRenderingStart viewHolder不为空");
                currentViewHolder.ivCover.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentViewHolder.startMusicAnim();
                        currentViewHolder.setCoverVisible(false);
                        if (shortVideoViewCallback != null) {
                            shortVideoViewCallback.beforePlay();
                        }
                    }
                }, 40);
            } else {
                KLog.i("=====onAudioRenderingStart viewHolder为空");
            }
        }

        @Override
        public void onPlayBufferStart() {
            super.onPlayBufferStart();
            if (currentViewHolder != null && !buffered) {
                currentViewHolder.showVideoLoading();
            }
        }

        @Override
        public void onPlayCompleted() {
            super.onPlayCompleted();
            buffered = true;
//            ShortVideoItem shortVideoItem = getItemData(currentPosition);
//            if (shortVideoItem != null) {
//                cacheNextVideo(shortVideoItem.getOpus_path(), false);
//            }
        }

        @Override
        public void onPlayBufferEnd() {
            super.onPlayBufferEnd();
            if (currentViewHolder != null) {
                currentViewHolder.dismissVideoLoading();
                if (buffered) {
                    currentViewHolder.setCoverVisible(false);
                }
            }
            if (shortVideoViewCallback != null) {
                shortVideoViewCallback.beforePlay();
            }
        }

        @Override
        public void onPlayStop() {
            showPauseState();
        }

        @Override
        public void onClickPause() {
            super.onClickPause();
            if (null != currentViewHolder) {
                currentViewHolder.dismissVideoLoading();
                currentViewHolder.setPlayIcon(false);
                currentViewHolder.pauseMusicAnim();
            }
        }

        @Override
        public void onPlayPause() {
            if (null != currentViewHolder) {
                KLog.i("=====视频暂停");
                currentViewHolder.dismissVideoLoading();
                currentViewHolder.setPlayIcon(true);
                currentViewHolder.pauseMusicAnim();
            }
        }

        @Override
        public void onPlayResume() {
            if (null != currentViewHolder) {
                currentViewHolder.dismissVideoLoading();
                currentViewHolder.setPlayIcon(true);
                currentViewHolder.resumeMusicAnim();
            }
        }

        @Override
        public void onPlayError(int errorCode) {
            showPauseState();
        }

        @Override
        public void onFileError(int code, String errorMessage) {
            if (code != 2) {
                ShortVideoItem shortVideoItem = getItemData(currentPosition);
                shortVideoItem.setIs_delete(1);
//            notifyItemChanged(currentPosition);
            }
            onVideoError(errorMessage);
        }

        @Override
        public void onPlayTimeCompleted(long videoId, String url, int videoDuring) {
            super.onPlayTimeCompleted(videoId, url, videoDuring);
            KLog.i("=======发送播放位置：videoId：" + videoId + " videoDuring:" + videoDuring);
            UserBehavior mUserBehavior = new UserBehavior(videoId, videoDuring, 0, 0);
            RxBus.getInstance().post(mUserBehavior);
        }

        @Override
        public void onDoubleClick(float x, float y) {
            super.onDoubleClick(x, y);
            if (currentViewHolder != null) {
                currentViewHolder.showLikeAnim(x, y);
            }
        }
    };

    //显示暂停状态
    private void showPauseState() {
        if (null != currentViewHolder) {
            currentViewHolder.dismissVideoLoading();
            currentViewHolder.setPlayIcon(false);
            currentViewHolder.pauseMusicAnim();
        }
    }

    /**
     * 首次激活播放器
     */
    public interface OnActiveCallback {
        void onActive();
    }

    //视频被删除了
    public void onVideoError(int position, long videoId, String message) {
        if (position > -1 && position < getDataContainer().size()) {
            ShortVideoItem shortVideoItem = getItemData(position);
            if (shortVideoItem != null && shortVideoItem.getId() == videoId) {//更新被删除视频的item
                refreshType = 4;
                shortVideoItem.setIs_delete(1);
                notifyItemChanged(position);
            }

            ShortVideoItem current = getItemData(currentPosition);
            if (current != null && current.getId() == videoId) {//如果是当前的正在播放的item
                ToastUtil.showToast(message);
                DcIjkPlayerManager.get().resetUrl();
                pausePlay();
                if (currentViewHolder != null) {
                    currentViewHolder.dismissVideoLoading();
                }
            }
        }
    }

    //刷新视频详情信息
    public void refreshVideoDetail(long videoId, int position, final ShortVideoInfoResponse videoInfoBean) {
        if (videoType == RecommendFragmentNew.TYPE_SINGLE_WORK) {//单个作品
            if (videoInfoBean != null && videoInfoBean.getOpus() != null) {
                if (videoId == videoInfoBean.getOpus().getId()) {
                    if (videoInfoBean.getOpus() != null) {
                        if (videoInfoBean.getUser() != null) {
                            videoInfoBean.getOpus().setUser(videoInfoBean.getUser());
                        }
                    }
                    videoInfoBean.getOpus().setLoaded(true);
                    currentPosition = 0;
                    addData(true, new ArrayList<ShortVideoItem>() {{
                        add(videoInfoBean.getOpus());
                    }}, false);
                } else {
                    showError(true);
                }
            } else {
                showError(true);
            }
        } else if (currentPosition > -1
                && currentPosition < getDataContainer().size()
                && null != videoInfoBean
                && position == currentPosition) {

            ShortVideoItem item = getDataContainer().get(currentPosition);
            if (null != item && videoId == item.getId()) {
                refreshType = 0;
                if (videoInfoBean.getOpus() != null) {
                    item.setComment_count(videoInfoBean.getOpus().getComment_count());
                    item.setShare_info(videoInfoBean.getOpus().getShare_info());
                    item.setIs_like(videoInfoBean.getOpus().is_like());
                    item.setIs_delete(videoInfoBean.getOpus().getIs_delete());
                    if (null != item.getShare_info() && videoInfoBean.getOpus().getShare_info() != null) {
                        item.getShare_info().setDownload_link(videoInfoBean.getOpus().getDownload_link());
                    }
                }
                if (videoInfoBean.getUser() != null) {
                    item.setUser(videoInfoBean.getUser());
                }
                item.setLoaded(true);
                notifyItemChanged(currentPosition, "2323");
            }
        }
    }

    //刷新评论数量
    public void refreshCommentCount(RefreshCommentBean bean) {
        if (currentPosition > -1
                && currentPosition < getDataContainer().size()
                && bean.position == currentPosition) {
            ShortVideoItem item = getDataContainer().get(currentPosition);
            if (null != item && item.getId() == bean.videoId) {
                refreshType = 1;
                item.setComment_count(bean.count);
                notifyItemChanged(currentPosition, "2323");
            }
        }
    }

    //刷新点赞
    public void refreshLike(int position, long videoId, ShortVideoLoveResponse bean) {
        if (currentPosition > -1
                && currentPosition < getDataContainer().size()
                && position == currentPosition) {
            ShortVideoItem item = getDataContainer().get(currentPosition);
            if (null != item && videoId == item.getId()) {
                refreshType = 2;
                item.setIs_like(bean.isIs_like());
                if (null != bean.getData_count()) {
                    item.setLike_count(bean.getData_count().getLike_count());
                }
                notifyItemChanged(currentPosition, "2323");
            }
        }
    }

    //刷新关注
    public void refreshFollow(int position, long videoId) {
        if (currentPosition > -1
                && currentPosition < getDataContainer().size()
                && position == currentPosition) {
            ShortVideoItem item = getDataContainer().get(currentPosition);
            if (null != item && videoId == item.getId()) {
                if (item.getUser() != null) {
                    refreshType = 3;
                    if (item.getUser().getRelation() == null) {
                        item.getUser().setRelation(new UserFanRelation());
                    }
                    item.getUser().getRelation().setIs_follow(true);
                    notifyItemChanged(currentPosition, "2323");
                }
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            //需要局部刷新的view
            if (holder instanceof RecommendNewViewHolder) {
                switch (refreshType) {
                    case 0://刷新评论数量
                        ((RecommendNewViewHolder) holder).setCommentCount();
                        ((RecommendNewViewHolder) holder).showFollow();
                        ((RecommendNewViewHolder) holder).setLike(false);
                        ShortVideoItem shortVideoItem = getItemData(currentPosition);
                        if (null != shortVideoItem && (shortVideoItem.getIs_delete() == 1)) {
                            onVideoError(DCApplication.getDCApp().getString(R.string.stringWorkDeleted));
                        }
                        break;
                    case 1://刷新评论数量
                        ((RecommendNewViewHolder) holder).setCommentCount();
                        break;
                    case 2://点赞
                        ((RecommendNewViewHolder) holder).setLike(true);
                        break;
                    case 3://关注
                        ((RecommendNewViewHolder) holder).showFollowAnim();
                        ((RecommendNewViewHolder) holder).setFollow();
                        break;
                    case 4:
                        ((RecommendNewViewHolder) holder).dismissVideoLoading();
                        break;
                }
            }
        }
    }

    private void onVideoError(String errorMessage) {
        findCurrentViewHolder();
        if (null != currentViewHolder) {
            currentViewHolder.dismissVideoLoading();
            currentViewHolder.setPlayIcon(true);
            currentViewHolder.setCoverVisible(true);
        }
        DcIjkPlayerManager.get().pausePlay();
        DcIjkPlayerManager.get().setClickPause(false);
        DcIjkPlayerManager.get().resetUrl();
        ToastUtil.showToast(errorMessage);
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        KLog.i("=========onViewAttachedToWindow:" + holder.getAdapterPosition());
        if (holder instanceof RecommendNewViewHolder) {
            ((RecommendNewViewHolder) holder).viewVisible();
            ((RecommendNewViewHolder) holder).getRootView().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != onActiveCallback) {
                        onActiveCallback.onActive();
                    }
                }
            }, 20);
        }
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        KLog.i("=========onViewDetachedFromWindow:" + holder.getAdapterPosition());
        if (holder instanceof RecommendNewViewHolder) {
            ((RecommendNewViewHolder) holder).setCoverVisible(true);
            ((RecommendNewViewHolder) holder).setPlayIcon(true);
            ((RecommendNewViewHolder) holder).releaseMusicAnim();
        }
    }

    /**
     * 恢复播放
     */
    public void resumePlay() {
        if (DcIjkPlayerManager.get().getPlayer() != null) {
            if (currentPosition > -1 && currentPosition < getDataContainer().size()) {
                ShortVideoItem shortVideoItem = getItemData(currentPosition);
                if (currentViewHolder != null && shortVideoItem != null) {
                    if (TextUtils.isEmpty(shortVideoItem.getOpus_path())
                            || shortVideoItem.getIs_delete() == 0) {
                        if (!shortVideoItem.getOpus_path().equals(DcIjkPlayerManager.get().getUrl())) {
                            DcIjkPlayerManager.get().attachPlayer(currentViewHolder.flPlayerContainer, new DcIjkPlayerManager.OnPlayerDetachListener() {
                                @Override
                                public void onDetach() {
                                    KLog.i("=======onDetach1 resumePlay");
                                    if (currentViewHolder != null) {
                                        KLog.i("=======onDetach2 resumePlay");
                                        currentViewHolder.setCoverVisible(true);
                                    }
                                }
                            });
                            buffered = false;
                            DcIjkPlayerManager.get().setVideoUrl(randomId, shortVideoItem.getId(), shortVideoItem.getOpus_path());
                        } else {
                            if (currentViewHolder.flPlayerContainer.getChildCount() == 0) {
                                DcIjkPlayerManager.get().attachPlayer(currentViewHolder.flPlayerContainer, new DcIjkPlayerManager.OnPlayerDetachListener() {
                                    @Override
                                    public void onDetach() {
                                        KLog.i("=======onDetach1 resumePlay");
                                        if (currentViewHolder != null) {
                                            KLog.i("=======onDetach2 resumePlay");
                                            currentViewHolder.setCoverVisible(true);
                                        }
                                    }
                                });
                            }
                            DcIjkPlayerManager.get().resumePlay(randomId);
                        }
                    } else {
                        onVideoError(DCApplication.getDCApp().getString(R.string.stringWorkDeleted));
                    }
                }
            }
        }
    }

    /**
     * 暂停播放
     */
    public void pausePlay() {
        DcIjkPlayerManager.get().pausePlay();
    }

    /**
     * 释放播放器
     */
    public void releasePlayer() {
        L.i("释放播放器");
        DcIjkPlayerManager.get().releasePlayer(true);
        if (cacheDisposable != null && !cacheDisposable.isDisposed()) {
            cacheDisposable.dispose();
        }
        if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
        compositeDisposable = null;
    }

    public void addDataList(boolean isRefresh, List<ShortVideoItem> newDataList) {
        resetPlay(isRefresh);
        addData(isRefresh, newDataList);
    }

    public void addDataList(boolean isRefresh, List<ShortVideoItem> newDataList, boolean hasMore) {
        resetPlay(isRefresh);
        addData(isRefresh, newDataList, hasMore);
    }

    private void resetPlay(boolean isRefresh) {
        if (isRefresh) {
            DcIjkPlayerManager.get().pausePlay();
            DcIjkPlayerManager.get().resetUrl();
            nextPosition = 0;
        }
    }

    public void setOnActiveCallback(OnActiveCallback onActiveCallback) {
        this.onActiveCallback = onActiveCallback;
    }

    private OnActiveCallback onActiveCallback;
}
